<template>
  <div class="ex-toolbar">
    <div class="ex-toolbar-header">
      <div class="ex-toolbar-header-left">
        <div class="ex-operation">
          <el-button :type="undoEnabled ? 'primary' : ''" :disabled="!undoEnabled" @click="handleRetreat" link>
            <el-icon class="ex-mgr-10" :size="20">
              <ex-icon-retreat />
            </el-icon>
          </el-button>
          <el-button :type="redoEnabled ? 'primary' : ''" :disabled="!redoEnabled" @click="handleAdvance" link>
            <el-icon class="ex-mgr-10" :size="20">
              <ex-icon-advance />
            </el-icon>
          </el-button>
        </div>
        <el-radio-group v-model="formConfig.patternType">
          <el-radio-button label="pc" class="font14">Pc</el-radio-button>
          <el-radio-button label="pad" class="font14">Pad</el-radio-button>
          <el-radio-button label="h5" class="font14">H5</el-radio-button>
        </el-radio-group>
        <!-- <el-button
          v-if="optionsData?.treeFormButton"
          @click="openWidgetTree"
          class="ex-mgl-10"
        >
          <div title="组件层次结构树">
            <el-icon :size="20">
            </el-icon>
          </div>
        </el-button> -->
      </div>
      <div class="flex" style="justify-content: center;align-items: center;">
        <div class="title">当前模版：{{ state.nameTxt }}</div>
        <el-popover placement="bottom" title="设置模板名" :width="'auto'" :visible="state.visible" trigger="click">
          <template #default>
            <div class="flex">
              <el-input v-model="state.nameInput" placeholder="必填不超过15个字" maxlength="15" style="width: 200px" />
              <el-button type="primary" class="ml10" plain
                @click=" state.visible = false; state.nameInput = '';">取消</el-button>
              <el-button type="primary" @click="saveName()">确定</el-button>
            </div>

          </template>
          <template #reference>
            <el-button link @click="state.visible = true">
              <el-icon><ele-Edit /></el-icon>
            </el-button>
          </template>
        </el-popover>
      </div>
      <el-scrollbar>
        <div class="ex-toolbar-header-right">

          <el-button @click="clear" link type="primary" class="font14">
            <el-icon>
              <ele-Delete />
            </el-icon>
            清空
          </el-button>
          <el-button v-if="optionsData?.previewFormButton" @click="openPreview" link type="primary" class="font14">
            <el-icon>
              <ele-View />
            </el-icon>
            预览
          </el-button>
          <el-button v-if="optionsData?.exportJsonButton" @click="openJsonDialog" link type="primary" class="font14">
            <el-icon><ele-Coin /></el-icon>

            保存
          </el-button>
          <!-- <el-button
            v-if="optionsData?.generateSFCButton"
            @click="openSFCDialog"
            link
            type="primary"
          >
            <el-icon><Coin /></el-icon>
            导出SFC
          </el-button> -->
        </div>
      </el-scrollbar>
    </div>
    <el-dialog v-model="isShowJSON" width="800" :title="title" @close="cancelJSONDialog" destroy-on-close draggable
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form">
        <el-form-item label="导出文件名">
          <el-input v-model="form.importName" />
        </el-form-item>
      </el-form>
      <ex-code-editor v-model="codeValue" :height="400" :dark="dark" :disabled="true" lang="json" />
      <template #footer>
        <span>
          <el-button v-if="optionsData?.copyDataButton" type="primary" v-copy="codeValue">复制内容</el-button>
          <!-- <el-button v-if="optionsData?.saveFileButton" type="primary" @click="importJSON">保存为文件</el-button> -->
          <el-button @click="cancelJSONDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="isShowSFC" width="800" :title="title" @close="cancelSFCDialog" draggable destroy-on-close
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form">
        <el-form-item label="导出文件名">
          <el-input v-model="form.importName" />
        </el-form-item>
        <el-form-item>
          <el-radio-group v-if="optionsData?.pageTypeButton" v-model="formConfig.isPageType" @change="changeRadio">
            <el-radio-button label="page">页面</el-radio-button>
            <el-radio-button label="dialog">弹框</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <ex-code-editor v-model="codeValue" :height="400" :dark="dark" :disabled="true" lang="vue" />
      <template #footer>
        <span>
          <el-button v-if="optionsData?.copyDataButton" type="primary" v-copy="codeValue">复制内容</el-button>
          <!-- <el-button v-if="optionsData?.saveFileButton" type="primary" @click="importSFC">
            保存为Vue3组件
          </el-button> -->
          <el-button @click="cancelSFCDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="isShowRender" fullscreen title="预览" @close="cancelRenderDialog" destroy-on-close center
      :close-on-click-modal="false">
      <div style="height: calc(90vh - 176px)">
        <ex-form-render ref="vFormRenderRef" :widget-list="widgetList" :form-config="formConfig" />
      </div>
      <template #footer>
        <div class="footer-btns">
          <el-button @click="openDefaultValueDialog" type="primary">
            获取数据
          </el-button>
          <el-button @click="handleResetForm" type="primary">
            重置表单
          </el-button>
          <el-button @click="handleOndisabled" type="primary">
            禁用编辑
          </el-button>
          <el-button @click="handleUndisable" type="primary">
            恢复编辑
          </el-button>
          <el-button @click="cancelRenderDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer size="300px" v-model="drawer" title="组件层次结构树" direction="ltr" @open="handleOpen" :before-close="close">
      <div class="ex-toolbar-drawer_tree">
        <el-tree ref="treeRef" :data="widgetList" :props="defaultProps" node-key="id" default-expand-all
          @node-click="handleNodeClick" :filter-node-method="filterNode" />
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, inject, reactive } from "vue";
// import FileSaver from "file-saver";
// import prettier from "prettier";
// import parserHtml from "prettier/plugins/html";
// import parserCss from "prettier/plugins/postcss";
// import parserBabel from "prettier/plugins/babel";
// import parserEstree from "prettier/plugins/estree";
// import { getSFCGenerator } from "/@/components/fromDesigner/core";
import { deepClone, onMessageWarning } from "/@/components/fromDesigner/utils";
import { DesFormWidget } from "/@/components/fromDesigner/core";
import { copy as vCopy } from "/@/components/fromDesigner/directives";
import { desPanelProps } from "./panel";
import { optionsKeys, darkKeys, formNameKeys, formIdKeys } from "../form-designer";
import { ElMessage } from "element-plus";
import { useFormDesignerApi } from '/@/api/formDesigner/index'
const formDesignerApi = useFormDesignerApi() //表单api
const props = defineProps(desPanelProps);

const optionsData = inject(optionsKeys);
const dark = inject(darkKeys);
const formName = inject(formNameKeys);
const formId = inject(formIdKeys);
const isShowJSON = ref(false);
const isShowSFC = ref(false);
const isShowRender = ref(false);
const title = ref("导出JSON");
const vFormRenderRef = ref();
const form = ref({ importName: "" });
const codeValue = ref("");
const treeRef = ref();
const drawer = ref(false);
const defaultProps = {
  children: "children",
  label: "id"
};
const state = reactive({
  nameTxt: <any>"", //展示的模版名称
  nameInput: "", //模版输出的名称
  visible: false, //气泡状态
  id: <any>"",//自定义表单ID
})


const undoEnabled = computed(() => props.designer.undoEnabled());
const redoEnabled = computed(() => props.designer.redoEnabled());

const clear = () => {
  props.designer.clearAllWidget();
};
const setFormId = () => {
  state.nameTxt = formName
  state.id = formId

}

setFormId()

const openWidgetTree = () => {
  drawer.value = true;
};

const handleAdvance = () => {
  props.designer.redoHistoryStep();
};

const handleRetreat = () => {
  props.designer.undoHistoryStep();
};

const openPreview = () => {
  isShowRender.value = true;
};

const openJsonDialog = () => {
  title.value = "导出JSON";
  form.value.importName = `form${new Date().getTime()}.json`;
  let widgetList = deepClone(props.designer.widgetList.value);
  // const jsonString = JSON.stringify(
  //   {
  //     formConfig: props.formConfig,
  //     widgetList
  //   },
  //   null,
  //   2
  // );
  if (state.nameTxt == '') {
    ElMessage.warning('请填写模板名称');
    return
  }
  const formData = {
    formConfig: props.formConfig,
    widgetList
  }

  let params = {
    id: state.id,
    name: state.nameInput,
    cover: '',
    value: formData
  }
  formDesignerApi.upsert(params).then(res => {
    ElMessage.success("保存成功")
  })

  // codeValue.value = jsonString;
  // isShowJSON.value = true;
}; //保存json 

const importJSON = () => {
  let bold = new Blob([codeValue.value], { type: "application/json" });
  // FileSaver.saveAs(
  //   bold,
  //   form.value.importName ?? `form${new Date().getTime()}.json`
  // );
};

const openSFCDialog = async () => {
  title.value = "生成SFC";
  form.value.importName = `form${new Date().getTime()}.vue`;
  await changeRadio();
  isShowSFC.value = true;
};

const changeRadio = async () => {
  let widgetList = deepClone(props.widgetList);
  let formConfig = deepClone(props.formConfig);
  // let code = getSFCGenerator({ widgetList, formConfig });
  // codeValue.value = await prettierCode(code);
};

// const importSFC = () => {
//   let bold = new Blob([codeValue.value], { type: "application/json" });
//   FileSaver.saveAs(
//     bold,
//     form.value.importName ?? `form${new Date().getTime()}.vue`
//   );
// };
// 格式化vue模板
// const prettierCode = async (code: string) => {
//   try {
//     return await prettier.format(code, {
//       parser: "vue",
//       plugins: [parserHtml, parserBabel, parserEstree, parserCss],
//       tabWidth: 2,
//       printWidth: 60,
//       trailingComma: "none",
//       htmlWhitespaceSensitivity: "ignore",
//       vueIndentScriptAndStyle: true,
//       singleAttributePerLine: true
//     });
//   } catch (error) {
//     return code;
//   }
// };

const openDefaultValueDialog = () => {
  title.value = "表单数据";
  form.value.importName = `form${new Date().getTime()}.json`;
  let data = vFormRenderRef.value.formData;
  console.log(data)
  // const jsonString = JSON.stringify(deepClone(data), null, 2);
  // codeValue.value = jsonString;
  // isShowJSON.value = true;
};

const handleResetForm = () => {
  vFormRenderRef.value.resetForm();
};

const handleOndisabled = () => {
  vFormRenderRef.value.ondisabled();
};

const handleUndisable = () => {
  vFormRenderRef.value.undisable();
};

const cancelJSONDialog = () => {
  isShowJSON.value = false;
};

const cancelSFCDialog = () => {
  isShowSFC.value = false;
};

const cancelRenderDialog = () => {
  isShowRender.value = false;
};

const handleOpen = () => {
  let id = props.designer.selectWidgetId.value;
  if (id) treeRef.value!.setCurrentKey(id);
  treeRef.value!.filter();
};

const filterNode = (value: string, data: DesFormWidget) => {
  return !(data.type === "table-td" && !data.merged);
};

const handleNodeClick = (data: DesFormWidget) => {
  if (["tab-pane", "table-tr"].includes(data.type)) {
    onMessageWarning("该节点不可选中");
    return;
  }
  props.designer.setSelectWidget(data);
};
const saveName = () => {
  if (!state.nameInput) {
    return ElMessage.error('请设置模版名称')
  } else {
    state.nameTxt = state.nameInput
    state.visible = false
  }

};//保存模版名称

const close = () => {
  drawer.value = false;
};
</script>
